package io.kiki.sba.registry.store.jdbc.repository.impl;

import io.kiki.sba.registry.store.api.date.DateNowRepository;
import io.kiki.sba.registry.store.jdbc.mapper.DateNowMapper;
import io.kiki.sba.registry.util.ConcurrentUtils;
import io.kiki.sba.registry.util.LoopExecuteTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.concurrent.TimeUnit;


public class DateNowJdbcRepository implements DateNowRepository {

    private static final Logger logger = LoggerFactory.getLogger(DateNowJdbcRepository.class);
    private final DateTimeWatcher watcher = new DateTimeWatcher();
    @Autowired
    DateNowMapper dateNowMapper;
    private volatile Date dateNow;

    @PostConstruct
    public void init() {
        ConcurrentUtils.createDaemonThread(this.getClass().getSimpleName() + "WatchDog", watcher).start();
    }

    @Override
    public Date getNow() {
        if (dateNow != null) {
            return dateNow;
        }
        dateNow = dateNowMapper.getNow().getNow();
        logger.info("[Load]getNow dateNow: {}", dateNow);
        return dateNow;
    }


    class DateTimeWatcher extends LoopExecuteTask {

        @Override
        public void _execute_() {
            dateNow = dateNowMapper.getNow().getNow();
            logger.info("[Load]watcher dateNow: {}", dateNow);
        }

        @Override
        public void _wait_() {
            ConcurrentUtils.sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
        }
    }
}
